package com.caipu.controller.admin;

import com.alibaba.fastjson.JSONObject;
import com.caipu.common.Result;
import com.caipu.dto.AiImageGenerateRequest;
import com.caipu.dto.AiImageTaskResponse;
import com.caipu.service.AiImageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

/**
 * AI图片生成管理控制器
 */
@Slf4j
@RestController
@RequestMapping("/admin/ai-image")
@RequiredArgsConstructor
@CrossOrigin(origins = "*")
public class AdminAiImageController {
    
    private final AiImageService aiImageService;
    
    /**
     * 生成AI图片
     */
    @PostMapping("/generate")
    public Mono<Result<?>> generateImage(@RequestBody AiImageGenerateRequest request) {
        log.info("开始生成AI图片，菜品名称: {}", request.getDishName());
        
        return aiImageService.generateImage(request)
                .map(response -> {
                    if (response.getErrorMessage() != null) {
                        return Result.error(response.getErrorMessage());
                    }
                    return Result.success(response);
                })
                .onErrorReturn(Result.error("AI图片生成服务异常"));
    }
    
    /**
     * 查询AI图片生成任务状态
     */
    @GetMapping("/task/{taskId}")
    public Mono<Result<AiImageTaskResponse>> getTaskStatus(@PathVariable String taskId) {
        log.info("查询AI图片任务状态，任务ID: {}", taskId);
        
        return aiImageService.getTaskStatus(taskId)
                .map(Result::success)
                .onErrorReturn(Result.error("查询任务状态失败"));
    }
    
    /**
     * 轮询获取生成结果
     */
    @GetMapping("/result/{taskId}")
    public Mono<Result<?>> getGeneratedImageUrl(@PathVariable String taskId) {
        log.info("获取AI图片生成结果，任务ID: {}", taskId);
        
        return aiImageService.getTaskStatus(taskId)
                .map(taskResponse -> {
                    if (taskResponse.getOutput() == null) {
                        return Result.error("任务信息获取失败");
                    }
                    
                    String status = taskResponse.getOutput().getTask_status();
                    if ("SUCCEEDED".equals(status)) {
                        if (taskResponse.getOutput().getResults() != null && 
                            !taskResponse.getOutput().getResults().isEmpty()) {
                            String imageUrl = taskResponse.getOutput().getResults().get(0).getUrl();
                            return Result.success(new JSONObject().fluentPut("status", "SUCCEEDED").fluentPut("imageUrl", imageUrl));
                        }
                        return Result.error("图片生成完成但未找到结果");
                    } else if ("FAILED".equals(status)) {
                        return Result.error("图片生成失败");
                    } else {
                        // PENDING 或 RUNNING 状态
                        return Result.success(new JSONObject().fluentPut("status", "PROCESSING")); // 特殊错误码表示还在处理中
                    }
                })
                .onErrorReturn(Result.error("获取生成结果失败"));
    }
}